var PushHandler = function () {
  this.onopen = function (e, ws) {
    // ws.send('hello 连上了哦')
    //document.getElementById('contentId').innerHTML += 'hello 连上了哦<br>';
    clientIndexHandleWsConn("onopen",e,ws);
  }

  /**
   * 收到服务器发来的消息
   * @param {*} event 
   * @param {*} ws 
   */
  this.onmessage = function (event, ws) {
    var data = event.data
    // console.log(data)
    if (typeof (data) == 'string') {
      data = JSON.parse(data);
    }
    clientIndexHandleMessage(data);
  }

  this.onclose = function (e, ws) {
    // error(e, ws)
    clientIndexHandleWsConn("onclose",e,ws);
  }

  this.onerror = function (e, ws) {
    // error(e, ws)
    clientIndexHandleWsConn("onerror",e,ws);
  }

  /**
   * 发送心跳，本框架会自动定时调用该方法，请在该方法中发送心跳
   * @param {*} ws 
   */
  this.ping = function (ws) {
    // log("发心跳了")
    ws.send('<#heartbeat#>')
  }
}

var ws_protocol = 'ws'; // ws 或 wss
var ws_ip = '127.0.0.1'
var ws_port = 9326

var heartbeatTimeout = 60000; // 心跳超时时间，单位：毫秒
var reconnInterval = 5000; // 重连间隔时间，单位：毫秒

var binaryType = 'blob'; // 'blob' or 'arraybuffer';//arraybuffer是字节
var handler = new PushHandler()
var default_deviceid = "screen_" + new Date().getTime();
var tiows
var ws_appid = "visual_client_andriod";
function initScreenWs(params) {

  if (!params) {
    params = {}
  }
  ws_protocol = params['ws_protocol'] || ws_protocol;
  ws_ip = params['ws_ip'] || ws_ip;
  ws_port = params['ws_port'] || ws_port;

  heartbeatTimeout = params['heartbeatTimeout'] || heartbeatTimeout;
  reconnInterval = params['reconnInterval'] || reconnInterval;

	var token = params['token'] || "";
  var deviceid = params['deviceid'] || default_deviceid;
  var deviceip = params['deviceip'] || "";
  ws_appid = params['appid'] || ws_appid;

  // 参数，get方式传递
  var queryString = "utype=client&appid=" + ws_appid + "&token=" + token + "&deviceid=" + deviceid + "&deviceip=" + deviceip;
  var param = queryString;
  tiows = new tio.ws(ws_protocol, ws_ip, ws_port, queryString, param, handler, heartbeatTimeout, reconnInterval, binaryType)

  tiows.connect()
}



function send() {
  var msg = document.getElementById('textId')
  tiows.send(msg.value)
}

function clearMsg() {
  document.getElementById('contentId').innerHTML = ''
}


function send2Server(msg) {
  // msg ，约定的消息格式
  var demo = {
    'msgType': 'event',//deviceinfo,devicestatus
    'data': {
      'eventKey': 'jieping',
      'content': ''
    }
  }
  tiows.send(msg)
}